#include "frhoadon_cthd.h"
#include "ui_frhoadon_cthd.h"
#include "qmessagebox.h"
#include "QModelIndex"
#include <QAbstractItemModel>
#include <QItemSelection>
#include <QItemSelectionModel>
#include "ketnoidb.h"

frHoaDon_CTHD::frHoaDon_CTHD(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::frHoaDon_CTHD)
{
    ui->setupUi(this);
    loadcbo();
    khoaDKPX(false);
    khoaDKCTP(false);
    loadPX();
    loadCTPX();
    ui->txtTenHang->setEnabled(false);
    connect(ui->tabPhieuXuat->selectionModel(),SIGNAL(selectionChanged(const QItemSelection &,const QItemSelection &)),this,SLOT(select(const QItemSelection &)));
}

frHoaDon_CTHD::~frHoaDon_CTHD()
{
    delete ui;
}

void frHoaDon_CTHD::loadPX()
{
    QSqlQueryModel *model = thaotac.truyVanDuLieu("SELECT m.MaPhieuXuat,m.MaDaiLy,d.TenDaiLy,m.TongTriGia,m.NgayLapPhieu FROM daily d,phieuxuat m WHERE d.MaDaiLy=m.MaDaiLy AND m.MaDaiLy="+QString::number(ui->cboMaDL_PX->currentIndex()+1));
    model->setHeaderData(0, Qt::Horizontal, QObject::trUtf8("Mã PX"));
    model->setHeaderData(1, Qt::Horizontal, QObject::trUtf8("Mã ĐL"));
    model->setHeaderData(2, Qt::Horizontal, QObject::trUtf8("Tên ĐL"));
    model->setHeaderData(3, Qt::Horizontal, QObject::trUtf8("Tổng GT"));
    model->setHeaderData(4, Qt::Horizontal, QObject::trUtf8("Ngày lập"));
    ui->tabPhieuXuat->setModel(model);
    ui->tabPhieuXuat->hideColumn(1);
    ui->tabPhieuXuat->show();
    connect(ui->tabPhieuXuat->selectionModel(),SIGNAL(selectionChanged(const QItemSelection &,const QItemSelection &)),this,SLOT(select(const QItemSelection &)));
     connect(ui->tabChiTietPhieu->selectionModel(),SIGNAL(selectionChanged(const QItemSelection &,const QItemSelection &)),this,SLOT(selectCT(const QItemSelection &)));
}

void frHoaDon_CTHD::select(QItemSelection)
{
    QAbstractItemModel *item=ui->tabPhieuXuat->model();
    QModelIndex indexItem=ui->tabPhieuXuat->currentIndex();
    int row=indexItem.row();
    ui->txtMaPX->setText(item->data(item->index(row,0)).toString());
    ui->txtTongGT_PX->setText(item->data(item->index(row,3)).toString());
    ui->dateNgayLap->setDate(item->data(item->index(row,4)).toDate());
    xoatext();
    loadCTPX();
}

void frHoaDon_CTHD::loadCTPX()
{
    QAbstractItemModel *item=ui->tabPhieuXuat->model();
    QModelIndex indexItem=ui->tabPhieuXuat->currentIndex();
    int row=indexItem.row();

    QSqlQueryModel *model = thaotac.truyVanDuLieu("SELECT c.MaChiTietPhieu,c.MaMatHang,m.TenMatHang,c.SoLuongXuat,c.DonViTinh,c.DonGia,c.ThanhTien,c.MaPhieuXuat FROM chitietphieuxuat c,mathang m WHERE c.MaMatHang=m.MaMatHang and c.MaPhieuXuat="+item->data(item->index(row,0)).toString());


    model->setHeaderData(0, Qt::Horizontal, QObject::trUtf8("Mã CTPX"));
    model->setHeaderData(1, Qt::Horizontal, QObject::trUtf8("Mã Hàng"));
    model->setHeaderData(2, Qt::Horizontal, QObject::trUtf8("Tên Hàng"));
    model->setHeaderData(3, Qt::Horizontal, QObject::trUtf8("Số Lượng"));
    model->setHeaderData(4, Qt::Horizontal, QObject::trUtf8("DVT"));
    model->setHeaderData(5, Qt::Horizontal, QObject::trUtf8("Đơn Giá"));
    model->setHeaderData(6, Qt::Horizontal, QObject::trUtf8("Thành Tiền"));
    model->setHeaderData(7, Qt::Horizontal, QObject::trUtf8("Mã PX"));


    ui->tabChiTietPhieu->setModel(model);
    ui->tabChiTietPhieu->show();
    ui->tabChiTietPhieu->hideColumn(1);
    ui->tabChiTietPhieu->hideColumn(7);
    ui->tabChiTietPhieu->hideColumn(0);

    connect(ui->tabChiTietPhieu->selectionModel(),SIGNAL(selectionChanged(const QItemSelection &,const QItemSelection &)),this,SLOT(selectCT(const QItemSelection &)));
}

void frHoaDon_CTHD::selectCT(QItemSelection)
{
    QAbstractItemModel *item=ui->tabChiTietPhieu->model();
    QModelIndex indexItem=ui->tabChiTietPhieu->currentIndex();
    int row=indexItem.row();

    ui->txtMaCTPX->setText(item->data(item->index(row,0)).toString());
    ui->txtDVT->setText(item->data(item->index(row,4)).toString());
    ui->txtGia->setText(item->data(item->index(row,5)).toString());
    ui->txtSoLuong->setText(item->data(item->index(row,3)).toString());
    ui->cboMatHang->setCurrentIndex(ui->cboMatHang->findText(item->data(item->index(row,1)).toString()));
    loadCTPX();
}

void frHoaDon_CTHD::loadcbo()
{
    ui->cboMaDL_PX->setModel(thaotac.truyVanDuLieu("select * from daily"));
    ui->cboMaDL_PX->setModelColumn(0);


    ui->cboMatHang->setModel(thaotac.truyVanDuLieu("select * from mathang"));
    ui->cboMatHang->setModelColumn(0);
}


void frHoaDon_CTHD::on_cboMaDL_PX_currentIndexChanged(const QString &arg1)
{
    QSqlQueryModel *model = thaotac.truyVanDuLieu("SELECT m.MaPhieuXuat,m.MaDaiLy,d.TenDaiLy,m.TongTriGia,m.NgayLapPhieu FROM daily d,phieuxuat m WHERE d.MaDaiLy=m.MaDaiLy AND m.MaDaiLy="+arg1);
    model->setHeaderData(0, Qt::Horizontal, QObject::trUtf8("Mã PX"));
    model->setHeaderData(1, Qt::Horizontal, QObject::trUtf8("Mã ĐL"));
    model->setHeaderData(2, Qt::Horizontal, QObject::trUtf8("Tên ĐL"));
    model->setHeaderData(3, Qt::Horizontal, QObject::trUtf8("Tổng GT"));
    model->setHeaderData(4, Qt::Horizontal, QObject::trUtf8("Ngày lập"));
    ui->tabPhieuXuat->setModel(model);
    ui->tabPhieuXuat->hideColumn(1);
    ui->tabPhieuXuat->show();

    ui->tabChiTietPhieu->setModel(false);
    QString tendl=laythongtinDaiLy(arg1);
    ui->lblTenDL->setText(tendl);
    connect(ui->tabPhieuXuat->selectionModel(),SIGNAL(selectionChanged(const QItemSelection &,const QItemSelection &)),this,SLOT(select(const QItemSelection &)));
}

void frHoaDon_CTHD::on_pushButton_clicked()
{
    if(QMessageBox::information(this,QString::fromUtf8("Thông báo!"),QString::fromUtf8("Bạn muốn thoát khỏi chương trình"),QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes)
        qApp->quit();
}

void frHoaDon_CTHD::on_btnThemPX_clicked()
{
    khoaDKPX(true);
    lenh="them";
    ui->txtTongGT_PX->setText("");
    ui->txtMaPX->setEnabled(false);
}

void frHoaDon_CTHD::on_btnSuaPX_clicked()
{
    lenh="sua";
    khoaDKPX(true);
    ui->txtMaPX->setEnabled(false);
}

void frHoaDon_CTHD::on_btnKLPX_clicked()
{
    khoaDKPX(false);
}

void frHoaDon_CTHD::on_btnLuu_PX_clicked()
{
    suathemPX(lenh);
    lenh="";
}



void frHoaDon_CTHD::on_btnThemCTP_clicked()
{
    lenh="them1";
    khoaDKCTP(true);
    ui->txtDVT->setText("");
    ui->txtGia->setText("");
    ui->txtSoLuong->setText("");

    ui->txtMaCTPX->setEnabled(false);
}

void frHoaDon_CTHD::on_btnKhogLCTP_clicked()
{
    khoaDKCTP(false);
}

void frHoaDon_CTHD::on_btnLuuCTP_clicked()
{
    suathemCTPX(lenh);
    loadCTPX();
}

void frHoaDon_CTHD::on_btnSuaCTP_clicked()
{
    lenh="sua1";

    khoaDKCTP(true);
    ui->txtMaCTPX->setEnabled(false);
}

void frHoaDon_CTHD::on_btnXoaCTP_clicked()
{
    if(ui->txtMaCTPX->text()=="")
    {
        QMessageBox::critical(this, QString::fromUtf8("Lỗi "), QString::fromUtf8("Chọn một phiếu xuất"));
        return;
    }
    if(QMessageBox::critical(this, QString::fromUtf8("Xóa !"),QString::fromUtf8("Có chắc chắn muốn xóa dữ liệu này ?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
    {
        QString str="DELETE FROM chitietphieuxuat WHERE machitietphieu=" + ui->txtMaCTPX->text() + " ";
        thaotac.capNhatDuLieu(str);
        loadCTPX();
    }
}



void frHoaDon_CTHD::on_btnXoaPX_clicked()
{
    if(ui->txtMaPX->text()=="")
    {
        QMessageBox::critical(this, QString::fromUtf8("Lỗi "), QString::fromUtf8("Chọn một phiếu xuất"));
        return;
    }
    QAbstractItemModel *item = ui->tabPhieuXuat->model();
    QModelIndex indexItem = ui->tabPhieuXuat->currentIndex();
    int row = indexItem.row();



    if(QMessageBox::critical(this, QString::fromUtf8("Xóa !"),QString::fromUtf8("Có chắc chắn muốn xóa dữ liệu này ?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
    {
         QString id = item->data(item->index(row,0)).toString();
         QString kt=kiemtra(id);
         if(kt!="")
         {
             if(QMessageBox::critical(this, QString::fromUtf8("Cảnh báo !"),QString::fromUtf8("Phiếu xuất này đã được nhập dữ liệu, bạn có chắc muốn xóa?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
             {
                 QString st="DELETE FROM chitietphieuxuat WHERE maphieuxuat=" + id + " ";
                 thaotac.capNhatDuLieu(st);

                 QString str="DELETE FROM phieuxuat WHERE maphieuxuat=" + id + " ";
                 thaotac.capNhatDuLieu(str);
             }
             else
                 {
                 return;
             }
         }
         else
         {
             QString str="DELETE FROM phieuxuat WHERE maphieuxuat=" + id + " ";
             thaotac.capNhatDuLieu(str);
         }
         loadPX();
    }
}

void frHoaDon_CTHD::khoaDKCTP(bool d)
{
    ui->btnKhogLCTP->setEnabled(d);
    ui->btnLuuCTP->setEnabled(d);
    ui->btnSuaCTP->setEnabled(!d);
    ui->btnThemCTP->setEnabled(!d);
    ui->btnXoaCTP->setEnabled(!d);

    ui->txtDVT->setEnabled(d);
    ui->txtGia->setEnabled(d);
    ui->txtMaCTPX->setEnabled(d);
    ui->txtSoLuong->setEnabled(d);
    ui->cboMatHang->setEnabled(d);

}
void frHoaDon_CTHD::khoaDKPX(bool d)
{
    ui->btnKLPX->setEnabled(d);
    ui->btnLuu_PX->setEnabled(d);
    ui->btnSuaPX->setEnabled(!d);
    ui->btnThemPX->setEnabled(!d);
    ui->btnXoaPX->setEnabled(!d);

    ui->txtMaPX->setEnabled(d);
    ui->txtTongGT_PX->setEnabled(d);
    ui->dateNgayLap->setEnabled(d);
}

void frHoaDon_CTHD::suathemPX(QString sss)
{
    if(sss=="them")
    {
        bool ok;
        ui->txtTongGT_PX->text().toInt(&ok);
        if(!ok)
        {
                QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "), QString::fromUtf8("Nhập tổng giá trị là số"));
                return;
        }

        thaotac.capNhatDuLieu("INSERT INTO phieuxuat(NgayLapPhieu,MaDaiLy,TongTriGia) values ('" + ui->dateNgayLap->text() + "'," + ui->cboMaDL_PX->currentText() + "," + ui->txtTongGT_PX->text()+ ") ");

        QMessageBox::information(this,QString::fromUtf8("Thông Báo"),QString::fromUtf8("Thêm phiếu xuất thành công"));

        loadPX();
        khoaDKPX(false);
    }
    if(sss=="sua")
    {
        bool ok;
        ui->txtTongGT_PX->text().toInt(&ok);
        if(!ok)
        {
                QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "), QString::fromUtf8("Nhập tổng giá trị là số"));
                return;
        }
        QAbstractItemModel *item = ui->tabPhieuXuat->model();
        QModelIndex indexItem = ui->tabPhieuXuat->currentIndex();
        int row = indexItem.row();
        QString str = "update phieuxuat set NgayLapPhieu='"+ui->dateNgayLap->text()+"',MaDaiLy="+ui->cboMaDL_PX->currentText()+""
                                ",TongTriGia="+ui->txtTongGT_PX->text()+" where maphieuxuat="+item->data(item->index(row,0)).toString()+"";
        query = thaotac.duyetDuLieu(str);

        loadPX();
        khoaDKPX(false);
    }
}

void frHoaDon_CTHD::suathemCTPX(QString sss)
{
    if(sss=="them1")
    {
        bool okk;
        ui->txtGia->text().toInt(&okk);
        if(!okk)
        {
                QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "), QString::fromUtf8("Nhập giá là số"));
                return;
        }
        bool ok;
        ui->txtSoLuong->text().toInt(&ok);
        if(!ok)
        {
                QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "), QString::fromUtf8("Nhập số lượng là số"));
                return;
        }

        if(ui->txtDVT->text()=="")
        {
            QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "), QString::fromUtf8("Nhập đơn vị tính"));
            return;
        }
        QAbstractItemModel *item=ui->tabPhieuXuat->model();
        QModelIndex indexItem=ui->tabPhieuXuat->currentIndex();
        int row=indexItem.row();
        float thanhtien=ui->txtGia->text().toFloat(0)*ui->txtSoLuong->text().toFloat(0);

        int sluong=laySoLuong(ui->cboMatHang->currentText());
        if(sluong<ui->txtSoLuong->text().toInt(0))
        {
            QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "),QString::fromUtf8("Nhập lượng hàng tồn kho còn ")+QString("%1").arg(sluong)+QString::fromUtf8(" vui lòng nhập lại."));
            return;
        }
        int sll=sluong-ui->txtSoLuong->text().toInt(0);
        QString strsl = "update mathang set soluongton="+ QString("%1").arg(sll) +" where mamathang="+ui->cboMatHang->currentText()+"";
        query = thaotac.duyetDuLieu(strsl);




        if(item->data(item->index(row,0)).toString()=="")
        {
            QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "), QString::fromUtf8("Chọn một phiếu xuất"));
            return;
        }
        QString sql="INSERT INTO chitietphieuxuat(MaMatHang,SoLuongXuat,DonViTinh,DonGia,ThanhTien,MaPhieuXuat) values (" +ui->cboMatHang->currentText()+","+ui->txtSoLuong->text()+",'"+ui->txtDVT->text()+"',"+ui->txtGia->text()+","+QString("%1").arg(thanhtien) +","+ item->data(item->index(row,0)).toString() + ") ";
        thaotac.capNhatDuLieu(sql);

        float tongtien=laythanhtien(item->data(item->index(row,0)).toString());
        QString strtt = "update phieuxuat set tongtrigia="+ QString("%1").arg(tongtien) +" where maphieuxuat="+item->data(item->index(row,0)).toString()+"";
        query = thaotac.duyetDuLieu(strtt);
        QMessageBox::information(this,QString::fromUtf8("Thông Báo"),QString::fromUtf8("Thêm thành công"));
        khoaDKCTP(false);
        loadPX();
    }
    if(sss=="sua1")
    {
        bool okk;
        ui->txtGia->text().toInt(&okk);
        if(!okk)
        {
                QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "), QString::fromUtf8("Nhập giá là số"));
                return;
        }
        bool ok;
        ui->txtSoLuong->text().toInt(&ok);
        if(!ok)
        {
                QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "), QString::fromUtf8("Nhập số lượng là số"));
                return;
        }
        //
        if(ui->txtDVT->text()=="")
        {
            QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "), QString::fromUtf8("Nhập đơn vị tính"));
            return;
        }

        if(ui->txtMaCTPX->text()=="")
        {
            QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "), QString::fromUtf8("Vui lòng chọn một chi tiết cần sửa."));
            return;
        }
            //a thay cai cbo no ko nhay dc do

        QAbstractItemModel *item=ui->tabPhieuXuat->model();
        QModelIndex indexItem=ui->tabPhieuXuat->currentIndex();
        int row=indexItem.row();
        int sluong=laySoLuong(ui->cboMatHang->currentText());
        if(sluong<ui->txtSoLuong->text().toInt(0))
        {
            QMessageBox::critical(this, QString::fromUtf8("Lỗi nhập đữ liệu "),QString::fromUtf8("Nhập lượng hàng tồn kho còn ")+QString("%1").arg(sluong)+QString::fromUtf8(" vui lòng nhập lại."));
            return;
        }
        int sll=sluong-ui->txtSoLuong->text().toInt(0);
        QString strsl = "update mathang set soluongton="+ QString("%1").arg(sll) +" where mamathang="+ui->cboMatHang->currentText()+"";
        query = thaotac.duyetDuLieu(strsl);


        float thanhtien=ui->txtGia->text().toFloat(0)*ui->txtSoLuong->text().toFloat(0);
        QString str = "update chitietphieuxuat set MaMatHang="+ui->cboMatHang->currentText()+",SoLuongXuat ="+ui->txtSoLuong->text()+",DonViTinh ='"+ui->txtDVT->text()+"',DonGia ="+ui->txtGia->text()+",ThanhTien ="+QString("%1").arg(thanhtien)+" where machitietphieu="+ui->txtMaCTPX->text()+"";
        query = thaotac.duyetDuLieu(str);



        if(query.numRowsAffected()==1)
        {
            float tongtien=laythanhtien(item->data(item->index(row,0)).toString());
            QString strtt = "update phieuxuat set tongtrigia="+ QString("%1").arg(tongtien) +" where maphieuxuat="+item->data(item->index(row,0)).toString()+"";
            query = thaotac.duyetDuLieu(strtt);
            QMessageBox::information(this,QString::fromUtf8("Thông Báo!"),QString::fromUtf8("Sửa Thành Công."));
        }
        else
        {
                QMessageBox::warning(this,QString::fromUtf8("Thông Báo!"),QString::fromUtf8("Sửa Không Thành Công."));
        }
        khoaDKCTP(false);
        loadPX();
    }
}

QString frHoaDon_CTHD::laythongtinMatHang(QString mahang)
{
    QString strsql="SELECT TenMatHang FROM mathang where MaMatHang="+mahang;
    QSqlQuery vl= thaotac.duyetDuLieu(strsql);
    vl.first();
    return vl.value(0).toString();
}


void frHoaDon_CTHD::on_cboMatHang_currentIndexChanged(const QString &arg1)
{
    QString ten=laythongtinMatHang(arg1);
    ui->txtTenHang->setText(ten);
}

QString frHoaDon_CTHD::laythongtinDaiLy(QString madl)
{
    QString strsql="SELECT TenDaiLy FROM daily where MaDaiLy="+madl;
    QSqlQuery vl= thaotac.duyetDuLieu(strsql);
    vl.first();
    return vl.value(0).toString();
}

void frHoaDon_CTHD::xoatext()
{
    ui->txtMaCTPX->setText("");
    ui->txtGia->setText("");
    ui->txtSoLuong->setText("");
    ui->txtDVT->setText("");

}

QString frHoaDon_CTHD::kiemtra(QString makt)
{
    QString strsql="SELECT machitietphieu FROM chitietphieuxuat where MaPhieuXuat="+makt;
    QSqlQuery vl= thaotac.duyetDuLieu(strsql);
    vl.first();
    return vl.value(0).toString();
}

float frHoaDon_CTHD::laythanhtien(QString tt)
{
    QString strsql="select sum(thanhtien) as tt from chitietphieuxuat where maphieuxuat="+tt;
    QSqlQuery vl= thaotac.duyetDuLieu(strsql);
    vl.first();
    return vl.value(0).toFloat(0);
}

int frHoaDon_CTHD::laySoLuong(QString sl)
{
    //
    QString strsql="select soluongton from mathang where mamathang="+sl;
    QSqlQuery vl= thaotac.duyetDuLieu(strsql);
    vl.first();
    return vl.value(0).toInt(0);
}
